﻿bob.ns.setNs('bob.string', {

    formatString: function (sFormat /*, arguments*/) {

        if (!bob.utils.isString(sFormat)) {
            throw new Error('Wrong argument: sFormat.');
        }

        var formatStringArgs = arguments;

        var result = sFormat.replace(/({)(\d+)(})/gi, function (fullMatch, openBracket, formatArgIndex, closeBracket, matchIndex, sInput) {
            var actualIndex = (formatArgIndex * 1) + 1;
            if (formatStringArgs.length < (actualIndex + 1)) {
                throw new Error(bob.string.formatString('Cannot format string: argument at index {0} not found.', formatArgIndex));
            }

            return formatStringArgs[actualIndex];
        });

        return result;
    },

    formatTemplate: function (sFormat, objParams, bIgnoreMissing) {

        if (!bob.utils.isString(sFormat)) {
            throw new Error('Wrong argument: sFormat.');
        }

        var result = sFormat.replace(/({)(\w+)(})/gi, function (fullMatch, openBracket, formatArgName, closeBracket, matchIndex, sInput) {
            if (!objParams.hasOwnProperty(formatArgName)) {
                if (bIgnoreMissing) {
                    return '';
                }
                else {
                    throw new Error(bob.string.formatString('Cannot format template: value for {0} not found.', formatArgName));
                }
            }

            return objParams[formatArgName];
        });

        return result;
    },

    //v3
    trim: function (sValue) {
        if (!bob.utils.isString(sValue)) {
            throw new Error('Wrong argument: sValue.');
        }

        if (String.prototype.trim) {
            return sValue.trim();
        }

        return sValue.replace(/^\s+|\s+$/g, '');
    }


});
